﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

public class BillboardWidget : MonoBehaviour
{
    private GameObject nameObjShadow;
    private GameObject nameObj;
    private TextMesh nameMeshShadow;
    private TextMesh nameMesh;
    private BaseEntity agent;
    private SortingGroup sortingGroup;

    public void setAgent(BaseEntity agent)
    {
        this.agent = agent;
    }

    //26  0.12 -0.01 0.01
    public void createBoard()
    {
        nameObjShadow = new GameObject(Billboard_Type.NamePart.ToString());
        nameObjShadow.transform.SetParent(this.transform);
        nameObjShadow.transform.localPosition = new Vector3(0, this.agent.HitBox.height + 0.5f, 0);
        nameMeshShadow = nameObjShadow.AddComponent<TextMesh>();
        nameMeshShadow.anchor = TextAnchor.MiddleCenter;
        nameMeshShadow.fontSize = 26;
        nameMeshShadow.characterSize = 0.12f;

        nameObj = GameObject.Instantiate(nameObjShadow);
        nameMesh = nameObj.GetComponent<TextMesh>();
        nameObj.transform.SetParent(nameObjShadow.transform);
        nameObj.transform.localPosition = new Vector3(-0.01f, 0.01f, 0);

        sortingGroup = nameObjShadow.AddComponent<SortingGroup>();
        refreshName();
        updateRenderSort();
    }

    public void refreshName()
    {
        if (nameMeshShadow != null)
        {
            nameMeshShadow.text = this.agent.RoleData.nickName;
            nameMeshShadow.color = Color.black;
        }
        if (nameMesh != null)
        {
            nameMesh.text = this.agent.RoleData.nickName;
            Color color = this.agent.UID == EntityMgr.Instance.mainRoleId ? new Color(255 / 255f, 183 / 255f, 0, 1) : new Color(255 / 255f, 219 / 255f, 37 / 255f, 1);
            nameMesh.color = color;
        }
    }

    private int maxOrder = 1000;
    private int magnifyOrder = 100;//放大倍率
    public void updateRenderSort() {
        if (sortingGroup) {
            float y = agent.DyBox.centerY - this.agent.DyBox.centerZ;
            int order = y > 0 ? maxOrder - Mathf.CeilToInt(y * magnifyOrder) : maxOrder + Mathf.CeilToInt(y * magnifyOrder) * -1;
            sortingGroup.sortingOrder = order;
        }
        
    }

}